<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 添加 Font Awesome 图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 添加样式 -->
    <style>
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            width: 80%;
            max-width: 500px;
            border-radius: 5px;
        }
        .close {
            float: right;
            cursor: pointer;
            font-size: 24px;
        }
        .pay-button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 15px;
        }
        .locked-chapter {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <ul class="chapter-list-1">
        <c:forEach var="chapter" items="${chapterList}" varStatus="status">
            <c:choose>
                <c:when test="${status.last}">
                    <!-- 最后一章 -->
                    <li class="locked-chapter" 
                        data-chapter-id="${chapter.chapter_id}"
                        onclick="showPaymentModal('${fn:escapeXml(chapter.title)}', '${chapter.chapter_id}', '${fn:escapeXml(novel.name)}')">
                        ${chapter.title}
                        <i class="fa-solid fa-lock" style="color: #bababa;"></i>
                    </li>
                </c:when>
                <c:otherwise>
                    <!-- 其他章节 -->
                    <a href="NovelContentServlet?chapter_id=${chapter.chapter_id}"><li>${chapter.title}</li></a>
                </c:otherwise>
            </c:choose>
        </c:forEach>
    </ul>

    <!-- 支付对话框 -->
    <div id="paymentModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h2>购买章节</h2>
            <div id="chapterInfo"></div>
            <button class="pay-button" onclick="processPayment()">立即支付</button>
        </div>
    </div>

    <script>
        function showPaymentModal(title, chapterId, novelName) {
            const modal = document.getElementById('paymentModal');
            const chapterInfo = document.getElementById('chapterInfo');

            // 存储所有需要的数据
            modal.dataset.chapterId = chapterId;
            modal.dataset.chapterTitle = title;
            modal.dataset.novelName = novelName;

            // 显示信息
            chapterInfo.innerHTML = `
                <p>小说：${novelName}</p>
                <p>章节：${title}</p>
                <p>价格：￥1</p>
                <p>购买后即可阅读</p>
            `;

            modal.style.display = 'block';
        }

        function closeModal() {
            const modal = document.getElementById('paymentModal');
            modal.style.display = 'none';
        }

        function processPayment() {
            const modal = document.getElementById('paymentModal');
            
            // 获取存储的所有数据
            const chapterId = modal.dataset.chapterId;
            const chapterTitle = modal.dataset.chapterTitle;
            const novelName = modal.dataset.novelName;
            
            // 发送请求到后端生成支付宝订单
            fetch('AlipayServlet', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    chapter_id: chapterId,
                    chapter_title: chapterTitle,
                    novel_name: novelName,
                    price: '1.00',  // 章节价格
                    subject: `${novelName} - ${chapterTitle}`, // 订单标题
                    body: `购买小说《${novelName}》的章节：${chapterTitle}`  // 订单描述
                })
            })
            .then(response => response.text())
            .then(htmlForm => {
                const div = document.createElement('div');
                div.innerHTML = htmlForm;
                document.body.appendChild(div);
                
                const form = div.querySelector('form');
                if (form) {
                    form.submit();
                } else {
                    throw new Error('支付表单生成失败');
                }
            })
            .catch(error => {
                console.error('支付错误:', error);
                alert('生成支付订单失败，请重试');
            });
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('paymentModal');
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }

        // 添加支付成功后的处理函数
        function handlePaymentSuccess(chapterId) {
            // 1. 找到对应的章节元素
            const lockedChapter = document.querySelector(`li[data-chapter-id="${chapterId}"]`);
            if (!lockedChapter) return;

            // 2. 移除锁图标
            const lockIcon = lockedChapter.querySelector('.fa-lock');
            if (lockIcon) {
                lockIcon.remove();
            }

            // 3. 移除点击事件，添加链接
            lockedChapter.onclick = null;
            lockedChapter.classList.remove('locked-chapter');
            
            // 4. 将章节转换为可点击链接
            const chapterLink = document.createElement('a');
            chapterLink.href = `NovelContentServlet?chapter_id=${chapterId}`;
            
            // 保存原有内容
            const chapterContent = lockedChapter.innerHTML;
            
            // 将章节包装在链接中
            while (lockedChapter.firstChild) {
                chapterLink.appendChild(lockedChapter.firstChild);
            }
            lockedChapter.appendChild(chapterLink);

            // 5. 关闭支付模态框
            closeModal();
        }

        // 修改支付成功回调页面的处理
        window.onPaymentSuccess = function(chapterId) {
            handlePaymentSuccess(chapterId);
            // 可以选择是否立即跳转到章节内容
            // window.location.href = `NovelContentServlet?chapter_id=${chapterId}`;
        };
    </script>
</body>
</html>